<template>
  <div class="search-result">
    <van-nav-bar
      :title="`${$route.query.keyword}的搜索结果`"
      left-arrow
      @click-left="$router.back()"
    />
    <van-empty v-if="results.length===0" image="search" description="暂无搜索结果" />
    <van-pull-refresh v-else v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group>
          <van-cell
            v-for="item in results"
            :key="item.art_id.toString()"
            :title="item.title"
            @click="$router.push({
              name: 'article',
              params: { id:item.art_id.toString() }
            })"
          >
            <template #label>
              <van-grid v-if="item.cover.type" :column-num="item.cover.type">
                <van-grid-item v-for="(v,i) in item.cover.images" :key="i">
                  <van-image :src="v" lazy-load />
                </van-grid-item>
              </van-grid>
              <div class="text">
                <span>{{ item.aut_name }}</span>
                <span>{{ item.comm_count }} 评论</span>
                <span>{{ item.pubdate | relativeTime }}</span>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getResult } from '@/api/search'
export default {
  name: 'SearchResult',
  data() {
    return {
      results: [],
      loading: false,
      finished: false,
      page: 1,
      refreshing: false
    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    // 加载
    async onLoad() {
      // 如果是重新加载,则清空列表,页数重新设为1,把loading设为true,再把refreshing设为false
      if (this.refreshing) {
        this.results = []
        this.page = 1
        this.loading = true
        this.refreshing = false
      }
      // 获取搜索结果
      const res = await getResult(this.$route.query.keyword, this.page, 10)
      // 页数+1
      this.page++
      // 合并结果
      this.results = [...this.results, ...res.data.results]
      // 将loading设为false
      this.loading = false
      // 如果结果是0条,则将finished设为false
      if (res.data.results.length === 0) this.finished = true
    },

    // 下拉刷新
    onRefresh() {
      // 执行onLoad函数,此时refreshing为true
      console.log('onRefresh触发了')
      this.onLoad()
    }
  }
}
</script>

<style lang="scss" scoped>
.van-nav-bar {
  ::v-deep {
    .van-nav-bar__title {
      letter-spacing: normal;
    }
  }
}
.text {
  span {
    margin-right: 10px;
  }
}
</style>
